package config

import (
	"fmt"
	"sync"

	"gitee.com/ironCoffers/goHelper/config/base"
)

//configCreatorMap 代表配置创建器的映射
var configCreatorMap = map[string]base.BaseConfig{}

//configMutex 代表配置创建器的映射专用锁
var configMutex sync.RWMutex

func RegisterConfig(name, fileName string, format base.ConfigFormat, notifyer base.Notifyer) error {
	if len(name) == 0 {
		return fmt.Errorf("config register error: name nil")
	}
	if len(fileName) == 0 {
		return fmt.Errorf("config register error: fileName is nil")
	}
	configMutex.Lock()
	defer configMutex.Unlock()
	if _, ok := configCreatorMap[name]; ok {
		return fmt.Errorf("config register error: already existing config for name %q", name)
	}
	switch format {
	default:
		config, err := DConfig(fileName)
		if err != nil {
			return err
		}
		configCreatorMap[name] = config
	case base.FORMAT_HOT:
		config, err := HConfig(fileName, notifyer)
		if err != nil {
			return err
		}
		configCreatorMap[name] = config
	}
	return nil
}

//Config 返回一个配置对象
func Config(name string) base.BaseConfig {
	configMutex.RLock()
	config, ok := configCreatorMap[name]
	configMutex.RUnlock()
	if ok {
		return config
	}
	return nil
}
